﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Lib.Helper;
using MSIACCSL2.CustomerServices;
using MSIACCSL2.InventoryServices;
using WcfService1.DTO;

namespace MSIACCSL2.Views.Import
{
    public partial class import_data : Page
    {

        public ExcelClass excelclass;
        String current = null;
        List<Stream> streams = new List<Stream>();
        List<string> stringTable = new List<string>();
        IEnumerable<List<string>> returnedlist = new List<List<string>>();
        List<string> listSheetNames = new List<string>();
        Stream getStyles = null;
        IEnumerable<List<string>> headers = new List<List<string>>();
        int getRowID = 0;
        bool loadingHeaders = false;
        public string name;
        private CustomerServicesClient customerClient;
        private InventoryServiceClient inventoryClient;

        public import_data()
        {
            InitializeComponent();
            customerClient = new CustomerServicesClient();
            inventoryClient = new InventoryServiceClient();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            getRowID = 1;
            listSheetNames.Clear();
            streams.Clear();
            FileNames.ItemsSource = null;
            Stream Wookbooknames = null;

            try
            {
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Filter = "xlsx (*.xlsx) |*.xlsx";
                UnZipper unzip;

                if ((bool)dialog.ShowDialog())
                {
                    Stream s = dialog.File.OpenRead();
                    unzip = new UnZipper(s);
                    Stream sharedStringsStream = s;
                    Stream WorkSheetStream = s;

                    foreach (string filename in unzip.GetFileNamesInZip())
                    {
                        Stream stream = unzip.GetFileStream(filename);
                        String filenameCompare = filename;
                        StreamReader reader = new StreamReader(stream);
                        String sharedStringsCompmare;
                        String findStyles;

                        findStyles = @"xl/styles.xml";

                        String findSheetsName = @"xl/workbook.xml";

                        sharedStringsCompmare = @"xl/sharedStrings.xml";

                        String filenamefind = @"xl/worksheets/";

                        if (filenameCompare.Contains(filenamefind) && filename.Contains("rels") == false)
                        {
                            streams.Add(stream);
                        }
                        if (filenameCompare == sharedStringsCompmare)
                        {
                            sharedStringsStream = stream;
                        }
                        if (filenameCompare == findStyles)
                        {
                            getStyles = stream;
                        }
                        if (filenameCompare == findSheetsName)
                        {
                            Wookbooknames = stream;

                        }
                    }

                    stringTable = ExcelClass.ReadStringTable(sharedStringsStream);

                    listSheetNames = ExcelClass.getWorkbookNames(Wookbooknames, streams.Count());

                    sharedStringsStream.Close();

                }

                FileNames.ItemsSource = listSheetNames;

                FileNames.Visibility = Visibility.Visible;

            }

            catch (IOException)
            {
                MessageBox.Show("File is in use - Please close the file and try again!");
            }
        }


        public IEnumerable<IDictionary> GenerateData(IEnumerable<List<string>> data, IEnumerable<List<string>> Headers)
        {

            var key = headers.First();
            var values = headers.Last();

            if (loadingHeaders == false)
            {

                grid1.Columns.Clear();

                for (int i = 0; i < key.Count(); i++)
                {
                    this.grid1.Columns.Add(
                    new DataGridTextColumn
                    {
                        Header = values[i],
                        Binding = new Binding(key[i])
                    });

                    loadingHeaders = true;
                }
            }

            foreach (List<string> row in data)
            {
                var dict = new Dictionary<string, object>();

                for (int j = 0; j < key.Count(); j++)
                {
                    dict[key[j]] = row[j];
                }
                yield return dict;

            }

        }

        private void FileNames_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           
        }

      

        private void btnCustomer_Click(object sender, RoutedEventArgs e)
        {
            var res = MessageBox.Show("Apakah Anda akan mengimpor ke data Customer?", "Confirmation", MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                var DataSource = grid1.ItemsSource;
                ObservableCollection<CustomerDTO> customers = new ObservableCollection<CustomerDTO>();
                    foreach (dynamic data in DataSource)
                    {
                        var customer = new CustomerDTO();
                        customer.CustomerId = data.A;
                        if (String.IsNullOrEmpty(customer.CustomerId))continue;
                        customer.CustomerName = data.B;
                        customer.Address = data.C;
                        customer.City = data.D;
                        customer.PostalCode = data.E;
                        customer.Country = data.F;
                        customer.Telp = data.G;
                        customer.Fax = data.H;
                        customer.Email = data.I;
                        customer.ContactPerson = data.J;
                        customers.Add(customer);
                    }

                    busy1.IsBusy = true;
                    customerClient.ImporCustomerCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(customerClient_ImporCustomerCompleted);
                    customerClient.ImporCustomerAsync(customers);
            }
        }

        void customerClient_ImporCustomerCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            customerClient.ImporCustomerCompleted -= new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(customerClient_ImporCustomerCompleted);
            if (e.Error != null)
                MessageBox.Show(e.Error.Message);
            else
                MessageBox.Show("Success");

            busy1.IsBusy = false;
            grid1.ItemsSource = null;
        }

        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            //ThreadPool.QueueUserWorkItem((x) =>
            //                                 {
            //                                     Dispatcher.BeginInvoke(new Action(()=>
            //                                                                           {

                                                                                           Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                                                                                           returnedlist = null;
                                                                                           if (FileNames.SelectedItem == null) return;
                                                                                           current = FileNames.SelectedItem.ToString();
                                                                                           object[] returnlists = new object[2];
                                                                                           int j = listSheetNames.Count() - 1;

                                                                                           for (int i = 0; i < listSheetNames.Count(); i++)
                                                                                           {
                                                                                               if (listSheetNames[i] == current)
                                                                                               {
                                                                                                   returnlists = ExcelClass.ReadWorksheet(streams[j], stringTable, getStyles, getRowID);
                                                                                               }
                                                                                               else
                                                                                               {
                                                                                                   j--;
                                                                                               }
                                                                                           }
                                                                                           returnedlist = (List<List<string>>)returnlists[0];
                                                                                           headers = (List<List<string>>)returnlists[1];

                                                                                           if (returnedlist.Count() == 0)
                                                                                           {
                                                                                               MessageBox.Show("Empty Workbook please select another");
                                                                                           }
                                                                                           else
                                                                                           {
                                                                                               grid1.ItemsSource = GenerateData(returnedlist, headers).ToDataSource();
                                                                                               grid1.Visibility = Visibility.Visible;
                                                                                           }

                                                                                          
                                             //                                          }));

                                             //});

           
        }

        private void btnInventory_Click(object sender, RoutedEventArgs e)
        {
            var res = MessageBox.Show("Apakah Anda akan mengimpor ke data Inventory?", "Confirmation", MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                var DataSource = grid1.ItemsSource;
                ObservableCollection<InventoryDTO> inventories = new ObservableCollection<InventoryDTO>();
                foreach (dynamic data in DataSource)
                {
                    var inventory = new InventoryDTO();
                    inventory.SerialNumber = data.A;
                    if (string.IsNullOrEmpty(inventory.SerialNumber)) continue;
                    inventory.NoBundle = int.Parse(data.B);
                    inventory.Description = data.C;
                    inventory.QtyPack = decimal.Parse(data.D);
                    inventory.QtyUnit = decimal.Parse(data.E);
                    inventory.UnitPrice = decimal.Parse(data.F);
                    inventory.Panjang = decimal.Parse(data.G);
                    inventory.Lebar = decimal.Parse(data.H);
                    inventory.Tinggi = decimal.Parse(data.I);
                    inventory.KodeMasuk = data.J;
                    inventory.Item = new ItemDTO() { ItemId = data.K};
                    inventory.SatuanPack = new SatuanDTO() { KodeSatuan = data.L };
                    inventory.SatuanUnit = new SatuanDTO() { KodeSatuan = data.M };
                    inventory.IsStock = Convert.ToBoolean(int.Parse(data.N));
                    inventory.Warehouses = new ObservableCollection<WarehouseDTO>();
                    var inventoryWarehouse = new WarehouseDTO();
                    inventoryWarehouse.KodeWarehouse = data.O;
                    inventoryWarehouse.Sheet = decimal.Parse(data.I);
                    inventoryWarehouse.Qty = decimal.Parse(data.E);
                    inventoryWarehouse.KodePallet = data.P;
                    inventory.Warehouses.Add(inventoryWarehouse);
                    inventories.Add(inventory);
                }

                busy1.IsBusy = true;

                inventoryClient.ImportInventoryCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(inventoryClient_ImportInventoryCompleted);
                inventoryClient.ImportInventoryAsync(inventories);
            }
        }

        void inventoryClient_ImportInventoryCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            inventoryClient.ImportInventoryCompleted -= new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(inventoryClient_ImportInventoryCompleted);
            if (e.Error != null)
                MessageBox.Show(e.Error.Message);
            else
                MessageBox.Show("Success");

            busy1.IsBusy = false;
            grid1.ItemsSource = null;
        }
            
       
      }

    
}
